/*
 * Copyright (c) www.bugull.com
 */

package com.bugull.farm.app.server.handler;

import com.bugull.farm.app.server.cache.AppCache;
import com.bugull.farm.core.cache.PropertiesCache;
import com.bugull.farm.core.server.ZKClient;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import org.apache.logging.log4j.*;

import java.util.concurrent.TimeUnit;

/**
 *
 * @author Frank Wen(xbwen@hotmail.com)
 */
public class AppChannelStatusHandler extends ChannelInboundHandlerAdapter {
    
    private final static Logger logger = LogManager.getLogger(AppChannelStatusHandler.class);
    private PropertiesCache props = PropertiesCache.getInstance();
    
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        //decrease channel count
        ZKClient.getInstance().decreaseChannelCount(props.get("zk.app.workers"));
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
    	//increase channel count
        ZKClient.getInstance().increaseChannelCount(props.get("zk.app.workers"));
        
        //if there is no join operation after the connection succeed for 10 seconds , then disconnect the connection
        ctx.channel().eventLoop().schedule(new Runnable() {
            @Override
            public void run() {
                AppCache cache = AppCache.getInstance();
                if(cache.getJoin(ctx.channel()) == null){
                    ctx.close();
                }
            }
        }, 10, TimeUnit.SECONDS);
    }
    
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
            throws Exception {
        cause.printStackTrace();
        logger.error(cause);
    }
}
